<template>
  <div>
    <myDivider name="小区管理"></myDivider>
    <!-- <el-alert :closable="false" title="三级菜单1" type="success" /> -->
    <el-page-header @back="goBack" :content="this.operateType == 'update' ? '修改小区信息' : '新增小区信息'">
    </el-page-header>
    <div class="insertPopulation">
      <el-form ref="reinsertForm" :model="reinsertForm" label-width="80px" :inline="true" :rules="insertRules">
        <el-form-item label="小区名称:" :label-width="formLabelWidth" class="formItemStyle" prop="name">
          <el-input v-model="reinsertForm.name" maxlength="50" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="所属管理处机构:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select @change="XuanZeJiGou" v-model="reinsertForm.affiliatedManagementCompanyId" placeholder="请选择"
            style="width: 262px;">
            <el-option v-for="item in affiliatedManagementCompanyIdData" :key="item.id" :label="item.shortName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属管理处部门:" :label-width="formLabelWidth" class="formItemStyle">
          <el-cascader change-on-select :disabled="reinsertForm.affiliatedManagementCompanyId == ''"
            v-model="reinsertForm.affiliatedManagementDepartmentIds" :options="affiliatedManagementDepartmentIdData"
            :props="{ value: 'id', label: 'name' }" style="width: 262px;"></el-cascader>
        </el-form-item>

        <el-form-item label="所属居委会机关:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.affiliatedAgencyId" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in affiliatedAgencyIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在地区:" :label-width="formLabelWidth" class="formItemStyle">
          <!-- <el-input v-model="reinsertForm.criCode" autocomplete="off" style="width: 500px"></el-input> -->
          <el-cascader ref="areas" v-model="reinsertForm.criCode" @focus="cascaderClick" :props="props"
            :options="options" @change="handleChange" style="width: 680px"></el-cascader>
        </el-form-item>

        <el-form-item label="详细地址:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input v-model="reinsertForm.address" maxlength="100" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="开发商机构:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.developerCompanyId" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in developerCompanyIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="承建商机构:" :label-width="formLabelWidth" class="formItemStyle">
          <el-select v-model="reinsertForm.contractorCompanyId" placeholder="请选择" style="width: 262px;">
            <el-option v-for="item in contractorCompanyIdData" :key="item.type" :label="item.name" :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开工日期:" :label-width="formLabelWidth" class="formItemStyle">
          <el-date-picker style="width: 262px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            v-model="reinsertForm.commencementDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="竣工日期:" :label-width="formLabelWidth" class="formItemStyle">
          <el-date-picker style="width: 262px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            v-model="reinsertForm.completionDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="入伙日期:" :label-width="formLabelWidth" class="formItemStyle">
          <el-date-picker style="width: 262px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            v-model="reinsertForm.checkInDate" type="date" placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="总建筑面积:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input maxlength="50" v-model="reinsertForm.totalBuildingArea" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="总占地面积:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input maxlength="50" v-model="reinsertForm.totalLandArea" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="绿化率百分比:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input maxlength="50" v-model="reinsertForm.greeningRate" autocomplete="off"
            style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="容积率:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input maxlength="50" v-model="reinsertForm.plotRatio" autocomplete="off" style="width: 262px"></el-input>
        </el-form-item>

        <el-form-item label="说明:" :label-width="formLabelWidth" class="formItemStyle">
          <el-input maxlength="200" v-model="reinsertForm.illustrate" autocomplete="off" style="width:680px"></el-input>
        </el-form-item>
      </el-form>

      <!-- 添加取消 -->
      <el-form ref="form" :model="reinsertForm" label-width="80px" style="height: 41px;">
        <el-form-item style="float: right; margin-bottom: 80px;">
          <el-button type="primary" @click="onSubmitUpdate" v-if="this.operateType == 'update'">修改</el-button>
          <el-button type="primary" @click="onSubmit" v-if="this.operateType == 'insert'">添加</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
    </div>
  </div>
</template>

<style lang="less" scoped>
.szdqBox {
  display: flex;

  .addressStyle {
    width: 350px;
    display: flex;
    justify-content: space-between;
    flex-wrap: nowrap;

    /deep/ label {
      width: 33%;

      select {
        width: 100%;
      }
    }
  }
}

.insertPopulation {
  margin-top: 90px;
  margin-left: 130px;
  height: 50%;
}

.menuTable {
  margin-top: 100px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.menuTable .cell {
  text-align: center;
}

.findValue {
  width: 13%;
  margin-top: 20px;
  margin-left: 15px;
}

.operation {
  margin-right: 50px;
  float: right;
  margin-top: 20px;
}

.formStyle {
  width: 1300px;
  margin: 20px auto;
}

.formItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}

.pageFooter {
  margin-top: 3%;
  margin-left: 40%;
}

.pageFooterFather {
  top: 84%;
  position: relative;
  width: 100%;
}

.el-cascader-menu {
  height: fit-content;
  width: fit-content;
}

.birthdayDateItemStyle {
  margin-bottom: 28px;
  margin-left: 22px;
}
</style>

<script>
import VDistpicker from "v-distpicker";
import { getUserList } from "../../user/user";
import {
  getFatherAgencies,
  addXiaoQu,
  getDictionaryList,
  getInDetail,
  updateinstInfo,
  getcityList,
  getJiGouList,
  getShangJiJiGouList,
  getJiGouBuMenList,
  getJiGuanList
} from "./residential";
export default {
  components: { VDistpicker },
  data() {
    var phonerule = (rule, value, callback) => {
      let pattern = /^1[3456789]\d{9}$/;
      if (!value) {
        return callback(new Error("手机号不能为空"));
      } else if (!pattern.test(value)) {
        return callback(new Error("请输入正确手机号"));
      } else {
        return callback();
      }
    };
    return {
      affiliatedManagementCompanyIdData: [
      ],
      affiliatedManagementDepartmentIdData: [
      ],
      affiliatedAgencyIdData: [
      ],
      developerCompanyIdData: [
        { name: '1号', type: 1 }
      ],
      contractorCompanyIdData: [
        { name: '1号', type: 1 }
      ],
      criCodeDefaultShow: true,
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          console.log(node,'qdqdccc');
          let { level } = node;
          getcityList(node.value).then(res => {
            res.forEach(el => {
              el.value = el.criCode;
              el.label = el.criName;
              el.leaf = level >= 3;
            });
            resolve(res);
          });
        }
      },
      options: [],

      // 是否认证
      authenticationStatusData: [
        { name: "未认证", id: "0" },
        { name: "已认证", id: "1" }
      ],
      formLabelWidth: "120px", //控制前面label的宽度

      reinsertForm: {
        name: "小区测试01", //小区名称
        affiliatedManagementCompanyId: 2, //所属管理处机构id
        affiliatedManagementDepartmentIds: 2, //所属管理处部门id
        affiliatedAgencyId: 2, //所属居委会机关id
        criCode: "130102001", //所在地code
        address: "怀特商城2302", //详细地址
        developerCompanyId: 8, //开发商机构id
        contractorCompanyId: 14, //承建商机构id
        commencementDate: "2022-01-01", //开工日期
        completionDate: "2023-12-01", //竣工日期
        checkInDate: "2023-12-02", //入伙日期
        totalBuildingArea: "50000.23", //总建筑面积
        totalLandArea: "51000.23", //总占地面积
        greeningRate: "40.12", //绿化率百分比
        plotRatio: "20.34", //容积率
        illustrate: "说明" //说明
      },
      insertRules: {
        name: [
          {
            required: true,
            message: "小区名称不能为空",
            trigger: "blur"
          }
        ]
      },
      operateType: "insert",
      genderListData: [
        { id: "0", name: "女" },
        { id: "1", name: "男" }
      ],
      typeOptionData: [],
      query: {
        name: "",
        account: ""
      },
      pageNum: 0,
      pageSize: 10,
      totalSize: 0
    };
  },

  activated() {
    this.getFatherAgenciesOptionData("");

    if (this.$route.query.operateType == "update") {
      this.getAgencyInfo(this.$route.query.id);
      this.operateType = "update";
    } else {
      // 数据清空
      for (let i in this.reinsertForm) {
        this.reinsertForm[i] = ''
      }
      this.operateType = "insert"
    }



  },
  mounted: function () {
    //初始化选项数据
    this.getAgencyTypeOptionData();
  },

  methods: {

    getAgencyInfo(id) {
      getInDetail(id).then(async res => {
        // this.XuanZeJiGou(res.affiliatedManagementCompanyId)
        this.XuanZeJiGou(2)
        console.log(res, '详细信息');
        // 先不让级联选择器设置为搜索
        this.props.lazy = false;
        // 挨个通过code值寻找下级孩子
        let arr = [
          "000000",
          res.provinceCriCode,
          res.cityCriCode,
          res.districtCriCode,
          res.criCode
        ];
        let res1 = await getcityList(arr[0]);
        let res2 = await getcityList(arr[1]);
        let res3 = await getcityList(arr[2]);
        let res4 = await getcityList(arr[3]);
        let res5 = await getcityList(arr[4]);
        this.options = [];
        res1.forEach(el => {
          this.options.push({
            value: el.criCode,
            label: el.criName,
            children: []
          });
        });
        this.options.forEach(el => {
          if (el.value == arr[1]) {
            res2.forEach(item => {
              el.children.push({
                value: item.criCode,
                label: item.criName,
                children: []
              });
            });
            el.children.forEach(dsc => {
              if (dsc.value == arr[2]) {
                res3.forEach(item => {
                  dsc.children.push({
                    value: item.criCode,
                    label: item.criName,
                    children: []
                  });
                });
              }
              dsc.children.forEach(dsic => {
                if (dsic.value == arr[3]) {
                  res4.forEach(item => {
                    dsic.children.push({
                      value: item.criCode,
                      label: item.criName
                    });
                  });
                }
              });
            });
          }
        });
        // 回复街道默认值
        this.reinsertForm.criCode = [
          res.provinceCriCode,
          res.cityCriCode,
          res.districtCriCode,
          res.criCode
        ]
        this.reinsertForm = res
        this.reinsertForm.affiliatedManagementDepartmentIds = JSON.parse(this.reinsertForm.affiliatedManagementDepartmentIds)
        console.log(this.reinsertForm, "详情信息");
        // 回显的时候 数字必须对应数字，字符串对应字符串
        this.reinsertForm.affiliatedManagementCompanyId = this.reinsertForm.affiliatedManagementCompanyId * 1
        this.reinsertForm.affiliatedAgencyId = this.reinsertForm.affiliatedAgencyId * 1
        this.reinsertForm.developerCompanyId = this.reinsertForm.developerCompanyId * 1
        this.reinsertForm.contractorCompanyId = this.reinsertForm.contractorCompanyId * 1


        for (let i in this.reinsertForm) {
          if (this.reinsertForm[i] == 0 && (i == 'developerCompanyId' || i == 'contractorCompanyId'|| i == 'affiliatedManagementCompanyId'|| i == 'affiliatedAgencyId')) {
            this.reinsertForm[i] = ''
          }
        }

      });
    },


    //级联选择器获取焦点
    cascaderClick() {
      this.getAgencyTypeOptionData();
      this.props.lazy = true;
    },
    handleChange(val) {
      console.log(val);
      this.reinsertForm.criCode = val[val.length - 1];
    },
    /**
     *  新增
     */
    onSubmit() {
      this.reinsertForm.affiliatedManagementDepartmentId = this.reinsertForm.affiliatedManagementDepartmentIds[this.reinsertForm.affiliatedManagementDepartmentIds.length - 1]

      this.reinsertForm.affiliatedManagementDepartmentIds = JSON.stringify(this.reinsertForm.affiliatedManagementDepartmentIds)
      let that = this;

      let params = {
        "name": this.reinsertForm.name, //小区名称
        "affiliatedManagementCompanyId": this.reinsertForm.affiliatedManagementCompanyId, //所属管理处机构id
        "affiliatedManagementDepartmentId": this.reinsertForm.affiliatedManagementDepartmentId, //所属管理处部门id
        "affiliatedManagementDepartmentIds": this.reinsertForm.affiliatedManagementDepartmentIds, //所属管理处部门层级 用于回显 String 类型 数组会报错
        "affiliatedAgencyId": this.reinsertForm.affiliatedAgencyId, //所属居委会机关id
        "criCode": this.reinsertForm.criCode, //所在地code
        "address": this.reinsertForm.address, //详细地址
        "developerCompanyId": this.reinsertForm.developerCompanyId, //开发商机构id
        "contractorCompanyId": this.reinsertForm.contractorCompanyId, //承建商机构id
        "commencementDate": this.reinsertForm.commencementDate, //开工日期
        "completionDate": this.reinsertForm.completionDate, //竣工日期
        "checkInDate": this.reinsertForm.checkInDate, //入伙日期
        "totalBuildingArea": this.reinsertForm.totalBuildingArea, //总建筑面积
        "totalLandArea": this.reinsertForm.totalLandArea, //总占地面积
        "greeningRate": this.reinsertForm.greeningRate, //绿化率百分比
        "plotRatio": this.reinsertForm.plotRatio, //容积率
        "illustrate": this.reinsertForm.illustrate //说明
      }
      console.log(params, "新增信息");
      this.$refs["reinsertForm"].validate(valid => {
        if (valid) {
          addXiaoQu(params).then(res => {
            console.log(res, "新增接口返回信息");
            if (res.code == 200) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.goBack();
            } else {
              if (res.message == "值重复") res.message = "机构名称不能重复";
              this.$message({
                message: res.message,
                type: "warning"
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    /**
     *  修改
     */
    onSubmitUpdate() {
      // 如果地区提交的是数组，只取最后的元素
      if (Array.isArray(this.reinsertForm.criCode)) {
        this.reinsertForm.criCode = this.reinsertForm.criCode[
          this.reinsertForm.criCode.length - 1
        ];
      }

      this.reinsertForm.affiliatedManagementDepartmentId = this.reinsertForm.affiliatedManagementDepartmentIds[this.reinsertForm.affiliatedManagementDepartmentIds.length - 1]
      this.reinsertForm.affiliatedManagementDepartmentIds = JSON.stringify(this.reinsertForm.affiliatedManagementDepartmentIds)
      this.reinsertForm.id = this.$route.query.id;
      let params = {
        "id": this.reinsertForm.id,
        "name": this.reinsertForm.name, //小区名称
        "affiliatedManagementCompanyId": this.reinsertForm.affiliatedManagementCompanyId, //所属管理处机构id
        "affiliatedManagementDepartmentId": this.reinsertForm.affiliatedManagementDepartmentId, //所属管理处部门id
        "affiliatedManagementDepartmentIds": this.reinsertForm.affiliatedManagementDepartmentIds, //所属管理处部门层级 用于回显 String 类型 数组会报错
        "affiliatedAgencyId": this.reinsertForm.affiliatedAgencyId, //所属居委会机关id
        "criCode": this.reinsertForm.criCode, //所在地code
        "address": this.reinsertForm.address, //详细地址
        "developerCompanyId": this.reinsertForm.developerCompanyId, //开发商机构id
        "contractorCompanyId": this.reinsertForm.contractorCompanyId, //承建商机构id
        "commencementDate": this.reinsertForm.commencementDate, //开工日期
        "completionDate": this.reinsertForm.completionDate, //竣工日期
        "checkInDate": this.reinsertForm.checkInDate, //入伙日期
        "totalBuildingArea": this.reinsertForm.totalBuildingArea, //总建筑面积
        "totalLandArea": this.reinsertForm.totalLandArea, //总占地面积
        "greeningRate": this.reinsertForm.greeningRate, //绿化率百分比
        "plotRatio": this.reinsertForm.plotRatio, //容积率
        "illustrate": this.reinsertForm.illustrate //说明
      }
      updateinstInfo(params).then(res => {
        if (res.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.goBack();
        } else {
          this.$message({
            message: res.message,
            type: "warning"
          });
        }
      });
    },

    /**
     *  上一页
     */
    goBack() {
      this.$router.push({ path: "/residential/reManagement" });
    },


    // 点击机构，获取机构下的部门
    async XuanZeJiGou(val) {
      console.log(val, '机构');
      // 机构下的部门
      let params = {
        "name": "",
        "unitType": "company", //必填 单位类型 机关:agency 机构:company
        "unitId": val //对应的机关机构id
      }
      let res = await getJiGouBuMenList(params)
      this.affiliatedManagementDepartmentIdData = res
      console.log(res, '机构部门列表');

    },


    /**
     * 获取type类型
     */
    async getFatherAgenciesOptionData(name) {

      // 获取机关列表 START
      let JiGuanData = await getJiGuanList()
      console.log(JiGuanData, 'JiGuanData');
      this.affiliatedAgencyIdData = []
      JiGuanData.forEach(el => {
        this.affiliatedAgencyIdData.push({
          name: el.name, type: el.id
        })
      })
      // 获取机关列表 END

      // 机构type类型获取
      let JiGouData = await getJiGouList('','')
      this.affiliatedManagementCompanyIdData = JiGouData
      console.log(JiGouData, 'JiGouData');

    },
    dgfun(res) {
      let arr = [];
      res.forEach(el => {
        // 如果有孩子们，继续遍历
        if (el.childrenList != null) {
          el.childrenList = this.dgfun(el.childrenList);
        }
        arr.push({
          value: el.criCode,
          label: el.criName,
          children: el.childrenList
        });
      });
      return arr;
    },
    /**
     * 获取类型字典数据
     */
    getAgencyTypeOptionData() {
      // 获取省份信息
      getcityList("000000").then(res => {
        this.options = [];
        res.forEach(el => {
          this.options.push({
            value: el.criCode,
            label: el.criName
          });
        });
      });
      getDictionaryList("agency_type").then(res => {
        this.typeOptionData = res.data;
      });
    },


  }
};
</script>
